package com.kui.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kui.annotation.AuthCheck;
import com.kui.common.BaseResponse;
import com.kui.common.DeleteRequest;
import com.kui.common.ResultUtils;
import com.kui.constant.UserConstant;
import com.kui.exception.ErrorCode;
import com.kui.exception.ThrowUtils;
import com.kui.model.dto.user.*;
import com.kui.model.entity.User;
import com.kui.model.vo.LoginUserVO;
import com.kui.model.vo.UserVO;
import com.kui.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/user")
@RestController
@Api(tags = "用户接口")
@Slf4j
public class UserController {
    //region 依赖注入
    @Resource
    private UserService userService;

    //endregion

    /**
     * 用户注册功能
     *
     * @param registerRequest
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
//    @AuthCheck(mustRole = UserConstant.ROLE_ADMIN)
    public BaseResponse<Long> userRegister(@RequestBody RegisterRequest registerRequest) {
        ThrowUtils.throwIf(registerRequest == null, ErrorCode.PARAMS_ERROR);
        Long resultId = userService.userRegister(registerRequest);
        return ResultUtils.success(resultId);
    }

    /**
     * 用户登录
     *
     * @param loginRequest
     * @param request
     * @return
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public BaseResponse<LoginUserVO> userLogin(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(ObjectUtils.isEmpty(loginRequest), ErrorCode.PARAMS_ERROR);
        LoginUserVO loginUserVO = userService.userLogin(loginRequest, request);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 获取到当前登录的用户
     *
     * @param request
     * @return
     */

    @GetMapping("get/login")
    @ApiOperation(value = "获取当前登录用户")
    public BaseResponse<LoginUserVO> getLoginUser(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        LoginUserVO loginUserVO = userService.loginUser(loginUser);
        return ResultUtils.success(loginUserVO);
    }

    /**
     * 用户退出登录
     *
     * @param request
     * @return
     */

    @PostMapping("/loginOut")
    @ApiOperation(value = "用户登出")
    public BaseResponse<Boolean> loginOut(HttpServletRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.NOT_LOGIN_ERROR, "用户未登录");
        Boolean b = userService.loginOut(request);
        return ResultUtils.success(b);
    }

    /**
     * 管理员增加用户
     *
     * @param userAddRequest
     * @return
     */
    @PostMapping("/add")
    @ApiOperation(value = "添加用户")
    @AuthCheck(mustRole = UserConstant.ROLE_ADMIN)
    public BaseResponse<Long> addUser(@RequestBody UserAddRequest userAddRequest) {
        ThrowUtils.throwIf(userAddRequest == null, ErrorCode.PARAMS_ERROR, "请求参数为空");
        User user = new User();
        BeanUtils.copyProperties(userAddRequest, user);
        //设置默认密码
        final String defaultPassword = "123456";
        user.setUserPassword(userService.encryptPassword(defaultPassword));
        boolean result = userService.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "添加失败");
        return ResultUtils.success(user.getId());
    }

    /**
     * 管理员根据id获取用户
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ROLE_ADMIN)
    @ApiOperation(value = "根据id获取用户")
    public BaseResponse<User> getUserById(String id) {
        int userId = Integer.parseInt(id);
        ThrowUtils.throwIf(StrUtil.isBlank(id), ErrorCode.PARAMS_ERROR, "id为空");
        ThrowUtils.throwIf(userId <= 0, ErrorCode.PARAMS_ERROR, "非法id");
        User user = userService.getById(userId);
        return ResultUtils.success(user);
    }

    /**
     * 根据id获取包装类用户
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    @ApiOperation(value = "根据id获取包装类用户")
    public BaseResponse<UserVO> getUserVoById(String id) {
        int userId = Integer.parseInt(id);
        ThrowUtils.throwIf(StrUtil.isBlank(id), ErrorCode.PARAMS_ERROR, "id为空");
        ThrowUtils.throwIf(userId <= 0, ErrorCode.PARAMS_ERROR, "非法id");
        BaseResponse<User> response = getUserById(id);
        User user = response.getData();
        return ResultUtils.success(userService.getUserVO(user));
    }

    /**
     * 管理员删除用户
     *
     * @param deleteRequest
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除用户")
    @AuthCheck(mustRole = UserConstant.ROLE_ADMIN)
    public BaseResponse<Boolean> deleteUser(@RequestBody DeleteRequest deleteRequest) {
        ThrowUtils.throwIf(deleteRequest == null || deleteRequest.getId() == null, ErrorCode.PARAMS_ERROR);
        boolean result = userService.removeById(deleteRequest.getId());
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "删除失败");
        return ResultUtils.success(result);
    }

    /**
     * 管理员更新用户
     *
     * @param userUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @ApiOperation(value = "更新用户")
    @AuthCheck(mustRole = UserConstant.ROLE_ADMIN)
    public BaseResponse<Boolean> updateUser(@RequestBody UserUpdateRequest userUpdateRequest) {
        ThrowUtils.throwIf(userUpdateRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        User user = new User();
        BeanUtils.copyProperties(userUpdateRequest, user);
        boolean update = userService.updateById(user);
        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "更新失败");
        return ResultUtils.success(true);
    }

    /**
     * 管理员分页查询用户
     *
     * @param userQueryRequest
     * @return
     */
    @PostMapping("/get/list/vo")
    @AuthCheck(mustRole = UserConstant.ROLE_ADMIN)
    @ApiOperation(value = "分页查询")
    public BaseResponse<Page<UserVO>> getUserPage(@RequestBody UserQueryRequest userQueryRequest) {
        // 抛出异常如果用户查询请求为空，指示参数错误
        ThrowUtils.throwIf(userQueryRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        // 从用户查询请求中获取当前页码和页面大小
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        // 执行用户分页查询
        Page<User> userPage = userService.page(new Page<>(current, pageSize), userService.getQueryWrapper(userQueryRequest));
        // 创建一个用户视图对象的分页，设置总记录数
        Page<UserVO> userVOPage = new Page<>(current, pageSize, userPage.getTotal());
        // 获取用户列表，并设置到用户视图对象的分页中
        List<UserVO> userList = userService.getUserList(userPage.getRecords());
        userVOPage.setRecords(userList);
        // 返回成功结果，包含用户视图对象的分页
        return ResultUtils.success(userVOPage);
    }


}
